package pt.isec.android.MyHistory;

import java.util.ArrayList;

import android.app.Service;
import android.content.ContentResolver;
import android.content.Context;
import android.content.Intent;
import android.database.Cursor;
import android.os.Bundle;
import android.os.IBinder;
import android.provider.BaseColumns;
import android.provider.CallLog;
import android.telephony.SmsManager;
import android.telephony.SmsMessage;
import android.telephony.TelephonyManager;
import android.util.Log;



public class MyHistoryCallService extends Service {
	private DataHelper dh;
	@Override
	public int onStartCommand(Intent intent, int flags, int startId) {
		final TelephonyManager phone;
		Log.d("servico","servico phone");
		
		phone=(TelephonyManager) this.getSystemService(this.TELEPHONY_SERVICE);
		int callState=phone.getCallState();
	

		switch (callState) 
		{
			case TelephonyManager.CALL_STATE_IDLE:
				Log.d("+++++Phone call+++++","idle");
				getLastCallLogEntry(this);
			break;
			case TelephonyManager.CALL_STATE_OFFHOOK:
				Log.d("+++++Phone call+++++","started");
				//out
			
				getLastCallLogEntry(this);
			break;
			case TelephonyManager.CALL_STATE_RINGING:
			
				Log.d("+++++Phone call+++++","ringing ");
				//in
			break;
		}
		
	

		

		return START_STICKY;
	
		}

private void getLastCallLogEntry( Context context ) {

		
		String[] strFields = {
		        android.provider.CallLog.Calls.NUMBER, 
		        android.provider.CallLog.Calls.TYPE,
		        android.provider.CallLog.Calls.CACHED_NAME
		        };
		String strOrder = android.provider.CallLog.Calls.DATE + " DESC"; 
		try {
			Thread.sleep(1000);
		} catch (InterruptedException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} 
		Cursor cur= context.getContentResolver().query(
		        android.provider.CallLog.Calls.CONTENT_URI,
		        strFields,
		        null,
		        null,
		        strOrder
		        );
		 
		
		int numberColumn = cur.getColumnIndex( CallLog.Calls.NUMBER );

		int typeColumn = cur.getColumnIndex( CallLog.Calls.TYPE );

		int nameColumn = cur.getColumnIndex(CallLog.Calls.CACHED_NAME);

		if( !cur.moveToNext()) {
			cur.close();
		}

		String number = cur.getString( numberColumn );

		String type = cur.getString( typeColumn );

		String name = cur.getString(nameColumn);
		
		Log.d("+++++Phone call+++++","Number: "+number+" Type: "+type+ "duration: "+name);
	
	}


	@Override
	public IBinder onBind(Intent arg0) {
		// TODO Auto-generated method stub
		return null;
	}

}
